<template>
  <div class="collection-view">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1 class="page-title">我的收藏</h1>
    </div>

    <!-- 收藏内容 -->
    <el-card class="collection-card">
      <!-- 收藏筛选和搜索 -->
      <div class="collection-header">
        <div class="search-filter">
          <el-input
            v-model="searchKeyword"
            placeholder="搜索收藏内容..."
            prefix-icon="Search"
            class="search-input"
            @keyup.enter="searchCollections"
          />
          
          <el-select v-model="collectionType" placeholder="选择收藏类型" class="filter-select">
            <el-option label="全部" value="all" />
            <el-option label="题目" value="question" />
            <el-option label="论坛帖子" value="forum" />
            <el-option label="学习资源" value="resource" />
          </el-select>
        </div>
        
        <div class="collection-actions">
          <el-button type="primary" @click="batchDeleteCollections" :disabled="selectedCollections.length === 0">
            <el-icon><Delete /></el-icon>
            批量删除
          </el-button>
        </div>
      </div>

      <!-- 收藏列表 -->
      <div class="collection-list">
        <el-table
          v-loading="loading"
          :data="filteredCollections"
          style="width: 100%"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" />
          
          <el-table-column prop="contentTitle" label="标题" width="400">
            <template #default="scope">
              <div class="collection-title">
                <router-link :to="getCollectionLink(scope.row)" target="_blank">
                  {{ scope.row.contentTitle }}
                </router-link>
              </div>
            </template>
          </el-table-column>
          
          <el-table-column prop="contentType" label="类型" width="120">
            <template #default="scope">
              <el-tag :type="getTagType(scope.row.contentType)">
                {{ isArticleType(scope.row) ? '文章' : getTypeName(scope.row.contentType) }}
              </el-tag>
            </template>
          </el-table-column>
          
          <el-table-column prop="source" label="来源" width="150" />
          
          <el-table-column prop="collectTime" label="收藏时间" width="180" />
          
          <el-table-column prop="viewCount" label="浏览次数" width="100" />
          
          <el-table-column label="操作" width="150" fixed="right">
            <template #default="scope">
              <el-button
                type="text"
                @click="deleteCollection(scope.row.id)"
                :confirm-message="`确定要删除收藏 '${scope.row.title}' 吗？`"
              >
                删除
              </el-button>
              <el-button type="text" @click="viewCollection(scope.row)">
                查看
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页 -->
      <div class="collection-pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalCollections"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  getUserCollections, 
  getUserCollectionsByType, 
  searchUserCollections,
  type CollectionItem,
  type CollectionResponse
} from '@/api/collection'

// 路由
const router = useRouter()

// 响应式数据
const searchKeyword = ref('')
const collectionType = ref('all')
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const totalCollections = ref(0)
const selectedCollections = ref<CollectionItem[]>([])

// 收藏数据
const collectionsData = ref<CollectionItem[]>([])


// 加载收藏数据
const loadCollections = async () => {
  try {
    loading.value = true
    const userId = localStorage.getItem('userId') || localStorage.getItem('user_id') || '1'
    
    console.log('开始加载收藏数据，用户ID:', userId)
    
    // 首先尝试从本地存储加载
    const collectionKey = `collections_${userId}`
    const localCollections = JSON.parse(localStorage.getItem(collectionKey) || '[]')
    console.log('本地存储的收藏数据:', localCollections)
    
    if (localCollections.length > 0) {
      console.log('使用本地存储的收藏数据:', localCollections.length)
      collectionsData.value = localCollections
      totalCollections.value = localCollections.length
      
      // 同时尝试从API同步数据（但不影响当前显示）
      try {
        let response: CollectionResponse
        
        if (searchKeyword.value.trim()) {
          response = await searchUserCollections(Number(userId), searchKeyword.value.trim(), {
            page: currentPage.value - 1,
            size: pageSize.value
          })
        } else if (collectionType.value !== 'all') {
          response = await getUserCollectionsByType(Number(userId), collectionType.value, {
            page: currentPage.value - 1,
            size: pageSize.value
          })
        } else {
          response = await getUserCollections(Number(userId), {
            page: currentPage.value - 1,
            size: pageSize.value
          })
        }
        
        // 如果API成功且有数据，使用API数据
        if (response && response.content && response.content.length > 0) {
          console.log('API数据加载成功，使用API数据')
          collectionsData.value = response.content
          totalCollections.value = response.totalElements
        } else {
          console.log('API返回空数据，继续使用本地数据')
        }
      } catch (apiError) {
        console.log('API加载失败，继续使用本地数据:', apiError)
      }
    } else {
      // 本地没有数据，尝试从API加载
      try {
        let response: CollectionResponse
        
        if (searchKeyword.value.trim()) {
          response = await searchUserCollections(Number(userId), searchKeyword.value.trim(), {
            page: currentPage.value - 1,
            size: pageSize.value
          })
        } else if (collectionType.value !== 'all') {
          response = await getUserCollectionsByType(Number(userId), collectionType.value, {
            page: currentPage.value - 1,
            size: pageSize.value
          })
        } else {
          response = await getUserCollections(Number(userId), {
            page: currentPage.value - 1,
            size: pageSize.value
          })
        }
        
        collectionsData.value = response.content || []
        totalCollections.value = response.totalElements || 0
        console.log('API数据加载成功')
      } catch (apiError) {
        console.error('API加载失败:', apiError)
        collectionsData.value = []
        totalCollections.value = 0
        ElMessage.info('暂无收藏数据')
      }
    }
    
  } catch (error) {
    console.error('加载收藏数据失败:', error)
    collectionsData.value = []
    totalCollections.value = 0
    ElMessage.error('加载收藏数据失败')
  } finally {
    loading.value = false
  }
}

// 计算属性：根据搜索和筛选条件过滤收藏
const filteredCollections = computed(() => {
  let filtered = [...collectionsData.value].filter(item => item && item.contentTitle && item.contentId)
  
  // 根据关键词搜索
  if (searchKeyword.value.trim()) {
    filtered = filtered.filter(item => 
      item.contentTitle.includes(searchKeyword.value.trim()) ||
      (item.contentDescription && item.contentDescription.includes(searchKeyword.value.trim()))
    )
  }
  
  // 根据类型筛选
  if (collectionType.value !== 'all') {
    filtered = filtered.filter(item => {
      // 对于文章类型，需要特殊处理，因为文章使用FORUM类型但URL包含/article/
      if (collectionType.value === 'article') {
        return item.contentUrl && item.contentUrl.includes('/article/')
      }
      return item.contentType.toLowerCase() === collectionType.value
    })
  }
  
  return filtered
})

// 获取收藏类型的标签类型
const getTagType = (type: string) => {
  const typeMap: Record<string, string> = {
    QUESTION: 'primary',
    FORUM: 'success',
    RESOURCE: 'warning',
    ARTICLE: 'info'
  }
  return typeMap[type] || 'default'
}

// 获取收藏类型的中文名称
const getTypeName = (type: string) => {
  const typeMap: Record<string, string> = {
    QUESTION: '题目',
    FORUM: '论坛帖子',
    RESOURCE: '学习资源',
    ARTICLE: '文章'
  }
  return typeMap[type] || type
}

// 根据URL判断是否为文章类型
const isArticleType = (item: CollectionItem) => {
  return item.contentUrl && item.contentUrl.includes('/article/')
}

// 获取收藏链接
const getCollectionLink = (item: CollectionItem) => {
  const linkMap: Record<string, string> = {
    QUESTION: `/search-question?id=${item.contentId}`,
    FORUM: `/forum/post/${item.contentId}`,
    RESOURCE: `/resources/detail/${item.contentId}`,
    ARTICLE: `/article/${item.contentId}`
  }
  return linkMap[item.contentType] || '/'
}

// 搜索收藏
const searchCollections = () => {
  currentPage.value = 1
}

// 处理选择变化
const handleSelectionChange = (val: any[]) => {
  selectedCollections.value = val
}

// 处理分页大小变化
const handleSizeChange = (size: number) => {
  pageSize.value = size
  currentPage.value = 1
}

// 处理当前页码变化
const handleCurrentChange = (current: number) => {
  currentPage.value = current
}

// 查看收藏
const viewCollection = (item: CollectionItem) => {
  const link = getCollectionLink(item)
  router.push(link)
}

// 删除单个收藏
const deleteCollection = async (id: string) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除该收藏吗？',
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const index = collectionsData.value.findIndex(item => item.id === Number(id))
    if (index > -1) {
      collectionsData.value.splice(index, 1)
      totalCollections.value -= 1
      
      // 同步到本地存储
      const userId = localStorage.getItem('userId') || localStorage.getItem('user_id') || '1'
      const collectionKey = `collections_${userId}`
      localStorage.setItem(collectionKey, JSON.stringify(collectionsData.value))
    }
    
    // 如果当前页没有数据了，返回上一页
    if (collectionsData.value.length === 0 && currentPage.value > 1) {
      currentPage.value -= 1
    }
    
    ElMessage.success('收藏删除成功')
  } catch (error) {
    // 用户取消操作
  }
}

// 批量删除收藏
const batchDeleteCollections = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedCollections.value.length} 个收藏吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 删除选中的收藏
    const selectedIds = selectedCollections.value.map(item => item.id)
    selectedIds.forEach(id => {
      const index = collectionsData.value.findIndex(item => item.id === Number(id))
      if (index > -1) {
        collectionsData.value.splice(index, 1)
        totalCollections.value -= 1
      }
    })
    
    // 同步到本地存储
    const userId = localStorage.getItem('userId') || localStorage.getItem('user_id') || '1'
    const collectionKey = `collections_${userId}`
    localStorage.setItem(collectionKey, JSON.stringify(collectionsData.value))
    
    // 清空选择
    selectedCollections.value = []
    
    // 如果当前页没有数据了，返回上一页
    if (collectionsData.value.length === 0 && currentPage.value > 1) {
      currentPage.value -= 1
    }
    
    ElMessage.success(`成功删除 ${selectedIds.length} 个收藏`)
  } catch (error) {
    // 用户取消操作
  }
}

// 组件挂载时初始化
onMounted(() => {
  loadCollections()
})
</script>

<style lang="scss" scoped>
.collection-view {
  padding: 20px;
  max-width: 1400px;
  margin: 0 auto;
}

.page-header {
  margin-bottom: 30px;
}

.page-title {
  font-size: 28px;
  font-weight: 600;
  color: #1f2937;
  margin: 0;
}

.collection-card {
  border-radius: 12px;
  overflow: hidden;
}

.collection-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #e5e7eb;
}

.search-filter {
  display: flex;
  gap: 15px;
  align-items: center;
}

.search-input {
  width: 300px;
}

.filter-select {
  width: 150px;
}

.collection-actions {
  display: flex;
  gap: 10px;
}

.collection-list {
  padding: 20px;
}

.collection-title a {
  color: #409eff;
  text-decoration: none;
  &:hover {
    text-decoration: underline;
  }
}

.collection-pagination {
  padding: 20px;
  display: flex;
  justify-content: flex-end;
  border-top: 1px solid #e5e7eb;
}
</style>